import request from '@/utils/request'
import _ from 'lodash'

const state = {
  directory: {},
  directoryItem: {},
  directoryItemDetail: {}
}

const mutations = {
  setDirectory: (state, code) => {
    if (!state.directory[code]) {
      request({
        url: '/preset/dictionary_param/queryParamsByCode',
        method: 'post',
        data: {
          code: code
        }
      }).then((res) => {
        if (res.result) {
          const data = res.data
          const keyValue1 = {}
          const keyValue2 = {}
          if (data) {
            data.forEach((param) => {
              keyValue1[param.data] = [param.label, param.extdata1]
              keyValue2[param.data] = param.label
            })
          }
          state.directoryItemDetail[code] = keyValue1
          state.directoryItem[code] = keyValue2
          state.directory[code] = res.data

          // 执行此方法字典才会被刷新
          state.directory = _.clone(state.directory)
          state.directoryItem = _.clone(state.directoryItem)
          state.directoryItemDetail = _.clone(state.directoryItemDetail)
        }
      })
    }
  }
}

const getters = {
  getDirectory: (state) => (code) => {
    return state.directory[code] || {}
  },
  getDirectoryKeys: (state) => (code) => {
    return state.directoryItem[code] || {}
  }
}

const actions = {

}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
